//  
//    UIView+Extension.swift
//    weibo
//  
//    Created by tianXin on 2017/3/3.
//    Copyright © 2017年 tianXin. All rights reserved.
//  

import UIKit

extension UIView {
    
    /**
     - returns: Filter the view controller.
     */
   
    func findViewController(sourceView:UIView?) -> (UIViewController?) {
        
        guard let sourceView =  sourceView else {
            
            return nil
        }
        
        var target = sourceView as UIResponder?
        
        while target != nil {
            
            target = target?.next
            if (target? .isKind(of: UIViewController.self))! {
                
                break;
            }
        }
        
        return target as? UIViewController
    }
    
    /**
     Get the view's screen shot, this function may be called from any thread of your app.
     - returns: The screen shot's image.
     */
    public func screenShot() -> UIImage? {
        
        guard height > 0 && width > 0 else {
            
            return nil
        }
        
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndPDFContext()
        
        return image
    }
    
    /**
     - Rotate Animation
     */
    func rotateViewAnimation()  {
        
        let tmpSpeed:TimeInterval   = 0.5
        let rotationAnimation       = CABasicAnimation(keyPath: "transform.rotation.z");
        rotationAnimation.fromValue = 0
        rotationAnimation.toValue   = (Double.pi/4)*100000
        rotationAnimation.duration  = tmpSpeed*100000
        rotationAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        
        self.layer.add(rotationAnimation, forKey: nil)
    }
}
